package com.ganzi.ganziserver.shiro.redis.OtherCache;


import com.ganzi.ganziserver.core.User;
import com.ganzi.ganziserver.dao.UserDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户缓存 根据sessionid
 * */
@Component
public class UserCache {

    @Autowired
    OtherCacheManager cacheManager;
    @Autowired
    UserDao useDao;


    public User getUser(String sessionId,String username){
        User u = null;
        try{
            u = getCacheUser(sessionId);
            if(u == null){
                User user =useDao.findUserByName(username);
                if(user != null){
                    u= user;
                    putCacheUser(sessionId,u);
                }
            }
        }catch (Exception e){
        }
        return u;
    }

    public User getUserByPrincipal(){
        User user =null;
        try{
            Subject subject = SecurityUtils.getSubject();
            String sessionId = (String)subject.getSession().getId();
            String username = (String)subject.getPrincipal();
            user = getUser(sessionId,username);
        }catch (Exception e){
        }
        return  user;
    }
    public long getUserIdByPrincipal(){
        User u = getUserByPrincipal();
        return u==null ? 0 : u.getId();
    }

    public User getCacheUser(String sessionId){
        User user = null;
        Cache<Object, Object> cache = cacheManager.getCache("user");
        user  = (User)cache.get(sessionId);
        return user;
    }

    public boolean putCacheUser(String sessionId,User user){
        Cache<Object, Object> cache = cacheManager.getCache("user");
        cache.put(sessionId,user);
        return true;
    }

    public void removeCacheUser(String sessionId){
        Cache<Object, Object> cache = cacheManager.getCache("user");
        cache.remove(sessionId);
    }
}
